require File.dirname(__FILE__) + "/serial.rb";
require "net/http";
require "uri";
require "hpricot";

class SearchSerials
  
  def self.search(keywords, format=nil)
    keywords = keywords.join(" ") if keywords.kind_of?(Array);
    results = search_google "(serial|serials) #{keywords}"
    results = results.map do |url, title|
      Serial.find_serials(get(url)).map{|serial| serial.serial;} rescue [];
    end
    results.flatten;
  end
 
  def self.search_google(query)
    results = get "http://www.google.com/search?q=#{URI.encode(query)}";
    results = Hpricot(results).search(".g a.l").map do |a|
      [a[:href], a.inner_text];
    end
    Hash[*results.flatten];
  end
 
  def self.get(url)
    Net::HTTP.get(URI.parse(url));
  end
 
end

p SearchSerials.search("photoshop")